<?php


namespace addons\facrm\controller;


use app\admin\model\Admin;
use EasyWeChat\Factory;
use think\addons\Controller;
use think\Hook;
use think\Log;
use think\Session;
use  app\admin\model\facrm\qywx\User as QywxUser;
use EasyWeChat\Kernel\Support;
use addons\facrm\library\BackendApi;

/**
 * 企业微信通信管理
 * @icon fa fa-circle-o
 */
class Qywx extends BackendApi
{
    protected $app = null;//EasyWeChat 实列
    protected $config = array();//企业微信配置
	protected $noNeedRight = ['*'];
    protected $noNeedLogin = ['connect','login','wxlogin'];

    public function _initialize()
    {
		//跨域请求检测
        check_cors_request();
        parent::_initialize();
        $this->request->filter(['strip_tags']);

        $key = "work_weixin_set";
        $settingModel = new \app\admin\model\facrm\Setting();
        $row = $settingModel->where('key', $key)->find();
        if (!$row) $this->error(__("企业微信未配置"));
        $this->config = json_decode($row['values'], true);//获取器不知道为什么失效了
        if (!$this->config) $this->error(__("企业微信未配置1"));

    }

    /**
     * 微信验证
     * @ApiInternal
     */
    public function connect()
    {

        $config = [
            'corp_id' => $this->config['corp_id'],
            'agent_id' => $this->config['agent_id'],
            'secret' => $this->config['agent_secret'],
            'token' => $this->config['customer_callback_token'],
            'aes_key' => $this->config['EncodongAESKey'],
        ];
        $app = Factory::work($config);
        $app->server->push(function($message){
            $res= \addons\facrm\library\qywx\Event::execute($message);
        });
        $response = $app->server->serve();
        $response->send();

    }

    /**
     * 企业微信H5登录
     * @ApiParams(name="code", type="string", required=true, description="post请求的时候需要")
     * @ApiParams(name="url", type="string", required=true, description="url")
     * @ApiBody ("get是获取一些基本配置")
     *
     */
    public function login(){
        $app_ag_config = [
            'corp_id' => $this->config['corp_id'],
            'agent_id' => $this->config['agent_id'],
            'secret' => $this->config['agent_secret'],
        ];

        if (request()->isGet()){
            $url = $this->request->param('url');
            $config = [
                'corp_id' => $this->config['corp_id'],
                'agent_id' => $this->config['agent_id'],
                'secret' => $this->config['customer_secret'],
            ];
            $this->app = $app = Factory::work($config);
            $wx_config = ($app->jssdk->buildConfig(['updateAppMessageShareData', 'updateTimelineShareData'], $debug = false, $beta = false, $json = true, $openTagList = []));

            $this->app = $app = Factory::work($app_ag_config);
            $supportExtend=new \addons\facrm\library\extend\easywechat\SupportExtend($app);
            $ag_config =  $supportExtend->buildAgentConfig(
                ['getCurExternalContact'],
                $this->config['agent_id'],
                $debug = false,
                $beta = false,
                $json = true,
                $openTagList = [],
                $url
            );

            $this->success('',['wx_config'=>json_decode($wx_config,true),'ag_config'=>json_decode($ag_config,true)]);
     
        }else{

            $app = Factory::work($app_ag_config);
            $user = $app->oauth->detailed()->user();
            // 获取用户信息
            $userid = $user->getId(); // 对应企业微信英文名（userid）
            if (!$userid) $this->error(__("获取企业微信信息失败"));

            $loca_user = QywxUser::getUser($userid);
            if (!$loca_user) {
                //不存在就调用接口去获取
                $c_config = [
                    'corp_id' => $this->config['corp_id'],
                    'secret' => $this->config['contacts_secret'], // 通讯录的 secret
                ];
                $contacts = Factory::work($c_config);
                $qywx_user = $contacts->user->get($userid);

                if (!$qywx_user || $qywx_user['errcode'] != '0') $this->error(__("获取企业微信信息失败"));
                $loca_user = QywxUser::getUser($userid, $this->config, $qywx_user);
            }

            if (!$loca_user || !$loca_user['admin_id']) {
                $this->error(__("企业微信登录失败"));
            }

            $admin = $this->auth->direct($loca_user['admin_id']);
            if ($admin) {
                Hook::listen("admin_login_after", $this->request);
                $this->success(__("登录成功！"), [
                    'token' => $admin->token,
                    'id' => $admin->id,
                    'username' => $admin->username,
                    'nickname' => $admin->nickname,
                    'avatar' => cdnurl($admin->avatar, true),
                ]);
            }
            $this->error(__($this->auth->getError()));

        }
        $this->error(__('登录失败'));

    }

    /**
     * 企业微信小程序登录
     * @ApiBody ("")
     *
     */
    public function wxlogin(){
        $config = [
            'corp_id' => $this->config['corp_id'],
            'agent_id' => $this->config['agent_id'],
            'secret' => $this->config['agent_secret'],
        ];

        $app = Factory::work($config);

        $miniProgram = $app->miniProgram();

        $res = $miniProgram->auth->session("js-code");

        if ($res&&isset($res['userid'])){
            $userid = $res['userid']; // 对应企业微信英文名（userid）
            if (!$userid) $this->error(__("获取企业微信信息失败"));

            $loca_user = QywxUser::getUser($userid);
            if (!$loca_user) {
                //不存在就调用接口去获取
                $c_config = [
                    'corp_id' => $this->config['corp_id'],
                    'secret' => $this->config['contacts_secret'], // 通讯录的 secret
                ];
                $contacts = Factory::work($c_config);
                $qywx_user = $contacts->user->get($userid);

                if (!$qywx_user || $qywx_user['errcode'] != '0') $this->error(__("获取企业微信信息失败"));
                $loca_user = QywxUser::getUser($userid, $this->config, $qywx_user);
            }

            if (!$loca_user || !$loca_user['admin_id']) {
                $this->error(__("企业微信登录失败"));
            }

            $admin = $this->auth->direct($loca_user['admin_id']);
            if ($admin) {
                Hook::listen("admin_login_after", $this->request);
                $this->success(__("登录成功！"), [
                    'token' => $admin->token,
                    'id' => $admin->id,
                    'username' => $admin->username,
                    'nickname' => $admin->nickname,
                    'avatar' => cdnurl($admin->avatar, true),
                ]);
            }
            $this->error(__($this->auth->getError()));
        }
		
		$this->error(__("获取企业微信信息失败2"));
    }

	
	 /**
     * 获取客户ID
     * @ApiParams(name="userid", type="string", required=true, description="企业微信客户")
     * @ApiBody ("get是获取一些基本配置")
     * @Internal
     */
    public function getCustomerId()
    {
        $admin = $this->auth->getUserInfo();
        if (!$admin) $this->error(__("未登录"));

        $external_userid = $this->request->param('userid');
        if (!$external_userid) $this->error(__("userid不能为空"));

        //获取本地微信外部联系人customer_id;
        $contactsModel = new \app\admin\model\facrm\qywx\Contacts();

        $qywxContacts = $contactsModel->getContacts($external_userid, $this->config, ['admin_id' => $admin['id']]);
        if (!$qywxContacts) {
            $this->error(__("获取企业客户信息失败"));
        }
        $this->success('', $qywxContacts->customer_id);
    }
	

}
